<script lang="ts" setup>
import { onMounted, ref, defineProps } from 'vue';
import { ApiConfigForm, KeyValues } from '../../utils/types';
import { paramDataTypeSelect  } from "../../utils"
import { apiAPI } from '../../api';

const props = defineProps<{
  apiId: any
}>()
const apiData = ref<ApiConfigForm>({
  name:'',
  originalPath:'',
  method:'',
  requestHeader:[],
  requestParam:[],
  requestPath:[]
})
const form = ref<KeyValues & { formParams: KeyValues[] }>({
  formParams: []
})
const emit = defineEmits([ 'submitted'])
const onTest = ()=>{
  emit('submitted',  form.value )
}


onMounted(()=>{
   apiAPI.get(props.apiId)
  .then(res => {
    apiData.value = res.data
    form.value = {
      apiId: apiData.value.apiId,
      versionId:apiData.value.versionId,
      formParams: [
        ...apiData.value.requestHeader.map( ( _: KeyValues) => { return { ..._, position: 'header'}}),
        ...apiData.value.requestParam.map( ( _: KeyValues) => { return { ..._, position: 'param'}}),
        ...apiData.value.requestPath.map( ( _: KeyValues) => { return { ..._, position: 'path'}}),
      ] 
    }
  })
})
</script>

<template>
  <div>
    <ElForm label-width="6em">
      <ElFormItem label="API名称">{{ apiData.name }}
      </ElFormItem>
      <ElFormItem label="请求Path">{{ apiData.originalPath }}
      </ElFormItem>
      <ElFormItem label="请求方式">{{ apiData.method }}</ElFormItem>
      <ElFormItem label="请求参数">
        <ElInput type="textarea" rows="8" v-model="form.jsonParams" placeholder="请输入入参" v-if="apiData.requestType=='application/json'"/>
        <ElTable :data="form.formParams" v-else>
          <ElTableColumn label="入参名称" prop="name" />
          <ElTableColumn label="参数位置" prop="position" />
          <ElTableColumn label="参数类型" prop="type">
            <template v-slot="{ row }">
             {{ paramDataTypeSelect.allTypes.find(_ =>_.value===row.type).label }} 
            </template>
          </ElTableColumn>
          <ElTableColumn label="是否必填" prop="isRequired">
            <template v-slot="{ row }">
             {{ row.isRequired? '是': '否' }} 
            </template>
          </ElTableColumn>
          <ElTableColumn label="参数值" width="160px">
            <template v-slot="{ row }">
              <ElInput v-model="row.value" placeholder="请输入"/>
            </template>
          </ElTableColumn>
        </ElTable>
      </ElFormItem>
      <ElFormItem>
        <ElButton type="primary" @click="onTest">发起调用</ElButton>
      </ElFormItem>
    </ElForm>
  </div>
</template>
